#include "settingswindow.h"
#include "ui_settingswindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>

SettingsWindow::SettingsWindow(settingsWindow &sw, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SettingsWindow),
    settings("settingWindow.ini"),
    settingsWin(sw)
{
    ui->setupUi(this);

    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setWindowModality(Qt::ApplicationModal);

    restoreSettings();
    uiInit();
}

SettingsWindow::~SettingsWindow()
{
    delete ui;
}

void SettingsWindow::closeEvent(QCloseEvent *event)
{
    settings.setValue("geometry", saveGeometry());
    QWidget::closeEvent(event);
}

void SettingsWindow::restoreSettings()
{
    if (settings.contains("geometry")) {
        restoreGeometry(settings.value("geometry").toByteArray());
    }
}

void SettingsWindow::uiInit()
{
    ui->checkBox_enableLogToFile->setChecked(settingsWin.log.enableToFile);
    ui->checkBox_enableTImeshift->setChecked(settingsWin.log.enableTimeshift);
    ui->checkBox_overwrite->setChecked(settingsWin.log.overwrite);
    ui->lineEdit_logFIlePath->setText(settingsWin.log.path);
    ui->spinBox_logFIleSizeLimit->setValue(settingsWin.log.maxSize);
}

void SettingsWindow::getSettings()
{
    settingsWin.log.enableTimeshift = ui->checkBox_enableTImeshift->isChecked();
    settingsWin.log.enableToFile = ui->checkBox_enableLogToFile->isChecked();
    settingsWin.log.overwrite = ui->checkBox_overwrite->isChecked();
    settingsWin.log.path = ui->lineEdit_logFIlePath->text();
    settingsWin.log.maxSize = ui->spinBox_logFIleSizeLimit->value();
}

void SettingsWindow::on_pushButton_save_clicked()
{
    QString logFilePath = ui->lineEdit_logFIlePath->displayText();
    if (logFilePath != ".") {
        QDir path(logFilePath);
        if (!path.exists()) {
            QMessageBox::critical(this, tr("错误！"), tr("保存失败，路径不合法"), tr("退出"));
            qDebug() << path.absolutePath() << " does not exists";
            return ;
        }
    }

    getSettings();
    emit sigSettingsValid(settingsWin);
}


void SettingsWindow::on_pushButton_quit_clicked()
{
    this->close();
}


void SettingsWindow::on_pushButton_selectLogPath_clicked()
{
    QString filename = QFileDialog::getExistingDirectory(this, "选择日志路径", ui->lineEdit_logFIlePath->displayText());
    if (filename == "") {
        return ;
    }
    qDebug("select log file path: %s", qPrintable(filename));

    ui->lineEdit_logFIlePath->setText(filename);
}


void SettingsWindow::on_pushButton_setDefault_clicked()
{
    settingsWindow sw = {.log{true, ".", 1024*1024*1024, false, true}};
    ui->checkBox_enableLogToFile->setChecked(sw.log.enableToFile);
    ui->checkBox_enableTImeshift->setChecked(sw.log.enableTimeshift);
    ui->checkBox_overwrite->setChecked(sw.log.overwrite);
    ui->lineEdit_logFIlePath->setText(sw.log.path);
    ui->spinBox_logFIleSizeLimit->setValue(sw.log.maxSize);
}

